﻿using jlynet.core.Library;
using jlynet.core.notebook.model;
using jlynet.core.notebook.util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace jlynet.core.notebook.myform
{
    public partial class LandingForm : Form
    {
        //数据库路径
        public string User_FilePath { get; set; }

        public LandingForm()
        {
            InitializeComponent();
            //this.MinimizeBox = false;  //去掉最小化
            this.MaximizeBox = false;  //去掉最大化

            if (!StringHelper.IsNullOrEmpty(User_FilePath)){
                this.textBox_createFilePath.Text = User_FilePath;
            }

            //当窗体启动时，读取INI文件的值并赋值给窗体
            this.Load += (s, e) =>
            {
                //form = new CreatePasswordBoxForm();
                INIFileInitialization n = new INIFileInitialization();
                this.textBox_createFilePath.Text = n.getDatabaseFilePath();

                INIHelper ini = new INIHelper(INIFileInitialization.INIPath);
                Point p = new Point();
                //判断返回值，避免第一次运行时为空出错  
                if ((ini.IniReadValue("LOC", "x") != "") && (ini.IniReadValue("LOC", "y") != ""))
                {
                    p.X = int.Parse(ini.IniReadValue("LOC", "x"));
                    p.Y = int.Parse(ini.IniReadValue("LOC", "y"));

                    // int.Parse将字符串转换为int  
                    this.Location = p;
                }
            };

            //窗口激活时候激活
            this.Activated += (s, e) => {
                INIFileInitialization n = new INIFileInitialization();
                this.textBox_createFilePath.Text = n.getDatabaseFilePath();
            };

            //关闭窗体触发
            this.FormClosing += (s, e) => {

            };

        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = Constant.DB_FileSuffix;
            //设置默认打开路径(绝对路径)
            dialog.InitialDirectory = @Library.SysHelper.GetStartupPath();
            // 显示对话框
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                // 文件名
                string fileName = dialog.FileName;
                this.textBox_createFilePath.Text = fileName;
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (!StringHelper.IsNullOrEmpty(this.textBox_password.Text) && !StringHelper.IsNullOrEmpty(this.textBox_createFilePath.Text)) {

                SQLiteConfigHelper.DatabaseFile = this.textBox_createFilePath.Text;

                Dictionary<string, object> parm = SQLiteUtil.getFileParameter(this.textBox_createFilePath.Text);

                string password = DESEncrypt.Encrypt(this.textBox_password.Text, Constant.DES_KEY);

                DataView dv = MySQLiteHelper.SelectDataView("select * from userInfoTable where id_='1' and file_path= ?;", new SQLiteParameter[] { new SQLiteParameter("file_path", parm["filename"]) });
                
                if (dv!=null)
                {
                    DataRowView row = dv[0];
                    string password_ = row["password"] != DBNull.Value ? row["password"].ToString() : "";
                    string problem = row["problem"] != DBNull.Value ? row["problem"].ToString() : "";
                    if (password_.Equals(password))
                    {
                        this.User_FilePath = this.textBox_createFilePath.Text;
                        this.DialogResult = DialogResult.OK;
                        //写入配置文件
                        INIFileInitialization ini = new INIFileInitialization();
                        if (File.Exists(INIFileInitialization.INIPath))
                        {
                            INIModel model = new INIModel();
                            model.node = "Options";
                            List<keyValue> keyValues = new List<keyValue>();
                            keyValue keyValue02 = new keyValue();
                            keyValue02.name = "LastFile";
                            keyValue02.value = SQLiteConfigHelper.DatabaseFile;
                            keyValues.Add(keyValue02);
                            model.keyValue = keyValues;
                            ini.initialization(model);
                        }
                        else
                        {
                            ini.initialization();
                        }
                        this.Close();
                        this.Dispose();
                    }
                    else if(!problem.Equals(""))
                    {
                        RecoverPasswordForm form = new RecoverPasswordForm();
                        form.ShowDialog(this);
                        this.Close();
                        this.Dispose(true);
                    }else
                    {
                        MessageBox.Show("密码错误！");
                        return;
                    }  
                }
                else{
                    MessageBox.Show("读取文件路径错误或密码错误！");
                    return;
                }
            }else{
                MessageBox.Show("读取文件路径错误或密码错误！");
                return;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //只是关闭当前窗口，若不是主窗体的话，是无法退出程序的，另外若有托管线程（非主线程），也无法干净地退出；
            //this.Close();
            ////强制所有消息中止，退出所有的窗体，但是若有托管线程（非主线程），也无法干净地退出；
            //Application.Exit();
            //强制中止调用线程上的所有消息，同样面临其它线程无法正确退出的问题；
            //Application.ExitThread();
            //这是最彻底的退出方式，不管什么线程都被强制退出，把程序结束的很干净。
            System.Environment.Exit(0);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CreatePasswordBoxForm form = new CreatePasswordBoxForm();
            form.ShowDialog(this);
            this.Close();
            this.Dispose();
        }
    }
}
